package cs5226.model;

import java.sql.Timestamp;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cs5226.util.StringUtil;

public class SingleValueStatistics {
	static Log log = LogFactory.getLog(SingleValueStatistics.class);
	
	private Timestamp ts;
	private double value;
	protected String name;

	public SingleValueStatistics(Timestamp ts, double value) {
		super();
		this.ts = ts;
		this.value = value;
	}
	
	public SingleValueStatistics (SingleValueStatistics svs) {
		this(svs.getTs(), svs.getValue());
	}

	public Timestamp getTs() {
		return ts;
	}

	public void setTs(Timestamp ts) {
		this.ts = ts;
	}
	
	public double getValue() {
		return value;
	}

	public void setValue(double value) {
		this.value = value;
	}

	public String getText() {
		return StringUtil.formatDouble(value);
	}
	
	public String getName() {
		return name;		
	}
	
	public SingleValueStatistics aggregate(List<SingleValueStatistics> statList) {
		if (statList == null || statList.size() == 0) return null;
		
		double agrVal = 0;
		for (int i=0; i<statList.size(); i++) {
			agrVal += statList.get(i).getValue(); 
			
		}
		return new SingleValueStatistics (statList.get(0).getTs(), agrVal/statList.size());
	}
	
	public <T> T toT(T t) {
		return (T) this;
	}
	
	public <T> T toT(Class<T> c) {
		try {
			return c.getConstructor(SingleValueStatistics.class).newInstance(this);		
		} catch (Exception e) {
			log.error("Unable to convert to class " + c.getName(), e);
			throw new RuntimeException(e);
		}		
	}
	
	public String toString () {
		return getText() + " at " + StringUtil.formatTimestamp(ts);
	}
	
	public String toHtml () {
		return "<span class='stat-value'>" + getText() + "</span><span class='stat-ts'> at " + StringUtil.formatTimestamp(ts) + "</span>";
	}

}
